package com.sibu.yx.promotion.common.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.util.List;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSONObject;
import com.doubo.common.util.ExceptionUtil;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class HttpClientUtil {

    public static CookieStore cookieStore = new BasicCookieStore();
    public static CloseableHttpClient httpCilent = HttpClients.custom().setDefaultCookieStore(cookieStore).build();

    public static JSONObject httpPostByJson(String url, JSONObject jsonObject) {
        HttpPost post = new HttpPost(url);
        String result = null;
        try {
            StringEntity s = new StringEntity(jsonObject.toString(),"UTF-8");
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json");//发送json数据需要设置contentType
            post.setEntity(s);
            HttpResponse res = httpCilent.execute(post);
            if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                result = EntityUtils.toString(res.getEntity());// 返回json格式：
            }
            }catch(Exception e){
                log.error(e.getMessage());
            }
            return JSONObject.parseObject(result);
        }

    public static String httpPost(String url, List<BasicNameValuePair> list) {

        // 配置超时时间
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(1000).setConnectionRequestTimeout(1000)
                .setSocketTimeout(1000).setRedirectsEnabled(true).build();

        HttpPost httpPost = new HttpPost(url);
        // 设置超时时间
        httpPost.setConfig(requestConfig);

        String strResult = "";
        int StatusCode=404;
        try {
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8");
            // 设置post求情参数
            httpPost.setEntity(entity);
            HttpResponse httpResponse = httpCilent.execute(httpPost);

            if (httpResponse != null) {
                StatusCode=httpResponse.getStatusLine().getStatusCode();
                if (httpResponse.getStatusLine().getStatusCode() == 200) {
                    strResult = EntityUtils.toString(httpResponse.getEntity());
                    return strResult;
                }  else {
                    strResult = "Error Response: " + httpResponse.getStatusLine().toString();
                    log.info("post/"+StatusCode+":"+strResult);
                    strResult=null;
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }

        return strResult;
    }

    public static InputStream getWxAcode(String postUrl, String outputStr) {
        HttpsURLConnection httpsUrlConn = null;
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader reader = null;
        StringBuffer resultBuffer = new StringBuffer();
        String tempLine = null;
        try {
            // 创建SSLcontext管理器对像，使用我们指定的信任管理器初始化
            TrustManager[] tm = { new MyX509TrustManager() };
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            SSLSocketFactory ssf = sslContext.getSocketFactory();

            URL url = new URL(postUrl);
            httpsUrlConn = (HttpsURLConnection) url
                    .openConnection();
            httpsUrlConn.setSSLSocketFactory(ssf);
            httpsUrlConn.setDoInput(true);
            httpsUrlConn.setDoOutput(true);
            httpsUrlConn.setUseCaches(false);
            httpsUrlConn.setConnectTimeout(30000);

            httpsUrlConn.setReadTimeout(30000);
            // 设置请求方式（GET/POST）
            httpsUrlConn.setRequestMethod("POST");
            httpsUrlConn.setRequestProperty(HTTP.CONTENT_TYPE, "application/json; charset=UTF-8");
            // 当有数据需要提交时
            if (outputStr != null) {
                OutputStream outputStream = httpsUrlConn.getOutputStream();
                // 防止中文乱码
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
                outputStream = null;
            }
            if (httpsUrlConn.getResponseCode() == HttpsURLConnection.HTTP_OK) {
                inputStream = httpsUrlConn.getInputStream();
                // 将返回的输入流转换成字符串
                if("image/jpeg".equalsIgnoreCase(httpsUrlConn.getContentType())) {
                    if (inputStream != null) {
                        return inputStream;
                    }
                } else {
                    inputStreamReader = new InputStreamReader(inputStream);
                    reader = new BufferedReader(inputStreamReader);
                    while ((tempLine = reader.readLine()) != null) {
                        resultBuffer.append(tempLine);
                    }
                    log.error("getWxAcode error:{}", resultBuffer.toString());
                    return null;
                }
            }
            return null;
        } catch (Exception e) {
            log.error("https request Exception, url:[{}], param:[{}], exception:[{}]", postUrl, outputStr, ExceptionUtil.getAsString(e));
        }
        return inputStream;
    }

    public static String httpGet(String url) {

        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000) // 设置连接超时时间
                .setConnectionRequestTimeout(5000) // 设置请求超时时间
                .setSocketTimeout(5000).setRedirectsEnabled(true)// 默认允许自动重定向
                .build();
        HttpGet httpGet2 = new HttpGet(url);
        httpGet2.setConfig(requestConfig);
        String srtResult =null;
        int StatusCode=404;
        try {
            HttpResponse httpResponse = httpCilent.execute(httpGet2);
            StatusCode=httpResponse.getStatusLine().getStatusCode();
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                srtResult = EntityUtils.toString(httpResponse.getEntity());// 获得返回的结果
                return srtResult;
            } else {
                srtResult = EntityUtils.toString(httpResponse.getEntity());// 获得返回的结果
                log.info("get/"+StatusCode+":"+srtResult);
                return null;
            }
        } catch (IOException e) {
            log.error("[{}]", e);
        }
        return null;
    }
    public static void setCookieStore(List<BasicClientCookie> cookielist ) {
        for(BasicClientCookie cookie:cookielist){
            HttpClientUtil.cookieStore.addCookie(cookie);
        }
    }
    public static void createCookie(List<BasicClientCookie> cookielist ) {
        for(BasicClientCookie cookie:cookielist){
            HttpClientUtil.cookieStore.addCookie(cookie);
        }
    }

}
